<template>
  <div class="p-4 mx-auto max-w-2xl">
    <h2 class="mb-4 text-xl font-bold">表情包生成器</h2>
    
    <!-- 图片上传区域 -->
    <div class="mb-6">
      <div 
        v-if="!imageUrl"
        class="flex flex-col justify-center items-center p-6 rounded-lg border-2 border-dashed cursor-pointer"
        :class="isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'"
        @dragenter.prevent="isDragging = true"
        @dragleave.prevent="isDragging = false"
        @dragover.prevent="isDragging = true"
        @drop.prevent="handleDrop($event)"
        @click="triggerFileInput"
      >
        <input 
          type="file" 
          ref="fileInput" 
          accept="image/*" 
          class="hidden"
          @change="handleFileChange"
        />
        
        <svg xmlns="http://www.w3.org/2000/svg" class="mb-2 w-12 h-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
        
        <p class="mb-1 text-gray-700">点击或拖拽图片到此处</p>
        <p class="text-sm text-gray-500">支持 JPG, PNG, WebP, GIF 格式</p>
      </div>
      
      <div v-else>
        <div class="relative mb-4">
          <!-- 表情包预览 -->
          <div ref="canvasContainer" class="flex justify-center">
            <canvas 
              ref="canvas" 
              class="max-w-full rounded border"
              @mousedown="startDragging"
              @touchstart="startDragging"
            ></canvas>
          </div>
          
          <!-- 图片操作按钮 -->
          <div class="flex gap-2 justify-center mt-2">
            <button @click="resetImage" class="px-3 py-1 text-sm text-white bg-red-500 rounded">
              重置图片
            </button>
            <button @click="chooseNewImage" class="px-3 py-1 text-sm text-white bg-blue-500 rounded">
              选择新图片
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 文本设置区域 -->
    <div v-if="imageUrl" class="mb-6">
      <h3 class="mb-2 font-bold">添加文字</h3>
      
      <div class="space-y-3">
        <!-- 顶部文字 -->
        <div>
          <label class="block mb-1 text-sm font-medium">顶部文字</label>
          <input 
            type="text" 
            v-model="topText" 
            class="p-2 w-full rounded border"
            placeholder="输入顶部文字"
            @input="drawMeme"
          />
        </div>
        
        <!-- 底部文字 -->
        <div>
          <label class="block mb-1 text-sm font-medium">底部文字</label>
          <input 
            type="text" 
            v-model="bottomText" 
            class="p-2 w-full rounded border"
            placeholder="输入底部文字"
            @input="drawMeme"
          />
        </div>
        
        <!-- 自定义文字 -->
        <div v-for="(text, index) in customTexts" :key="index" class="relative">
          <div class="flex gap-2">
            <input 
              type="text" 
              v-model="text.content" 
              class="flex-1 p-2 rounded border"
              :placeholder="`自定义文字 ${index + 1}`"
              @input="drawMeme"
            />
            <button 
              @click="removeCustomText(index)" 
              class="px-3 py-1 text-white bg-red-500 rounded"
            >
              删除
            </button>
          </div>
          <div class="mt-1 text-xs text-gray-500">
            <span>位置: ({{ Math.round(text.x) }}, {{ Math.round(text.y) }})</span>
            <span class="ml-2">可拖动调整位置</span>
          </div>
        </div>
        
        <button 
          @click="addCustomText" 
          class="px-4 py-2 text-white bg-green-500 rounded"
        >
          添加自定义文字
        </button>
      </div>
      
      <!-- 文字样式设置 -->
      <div class="mt-4 space-y-3">
        <h4 class="font-medium">文字样式</h4>
        
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block mb-1 text-sm">字体</label>
            <select v-model="textStyle.font" class="p-2 w-full rounded border" @change="drawMeme">
              <option value="Impact">Impact (梗图常用)</option>
              <option value="Arial">Arial</option>
              <option value="Microsoft YaHei">微软雅黑</option>
              <option value="SimHei">黑体</option>
              <option value="SimSun">宋体</option>
              <option value="Comic Sans MS">Comic Sans MS</option>
            </select>
          </div>
          
          <div>
            <label class="block mb-1 text-sm">字体大小</label>
            <div class="flex items-center">
              <input type="range" v-model="textStyle.size" min="12" max="72" @input="drawMeme" class="flex-1 mr-2" />
              <span>{{ textStyle.size }}px</span>
            </div>
          </div>
        </div>
        
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block mb-1 text-sm">文字颜色</label>
            <input type="color" v-model="textStyle.color" @input="drawMeme" class="w-full h-10 rounded border" />
          </div>
          
          <div>
            <label class="block mb-1 text-sm">描边颜色</label>
            <input type="color" v-model="textStyle.strokeColor" @input="drawMeme" class="w-full h-10 rounded border" />
          </div>
        </div>
        
        <div>
          <label class="block mb-1 text-sm">描边宽度</label>
          <div class="flex items-center">
            <input type="range" v-model="textStyle.strokeWidth" min="0" max="8" step="0.5" @input="drawMeme" class="flex-1 mr-2" />
            <span>{{ textStyle.strokeWidth }}px</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 导出选项 -->
    <div v-if="imageUrl" class="mb-6">
      <h3 class="mb-2 font-bold">导出选项</h3>
      
      <div class="flex flex-wrap gap-2">
        <button @click="downloadMeme('png')" class="px-4 py-2 text-white bg-blue-500 rounded">
          保存为PNG
        </button>
        <button @click="downloadMeme('jpg')" class="px-4 py-2 text-white bg-green-500 rounded">
          保存为JPG
        </button>
        <button @click="copyToClipboard" class="px-4 py-2 text-white bg-purple-500 rounded">
          复制到剪贴板
        </button>
      </div>
    </div>
    
    <!-- 模板选择 -->
    <div v-if="!imageUrl" class="mb-6">
      <h3 class="mb-2 font-bold">或选择热门模板</h3>
      <div class="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
        <div 
          v-for="(template, index) in memeTemplates" 
          :key="index"
          class="overflow-hidden rounded border cursor-pointer"
          @click="useTemplate(template)"
        >
          <img :src="template.url" :alt="template.name" class="object-cover w-full h-24" />
          <div class="p-1 text-xs text-center truncate">{{ template.name }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'

// 图片和画布
const fileInput = ref(null)
const canvas = ref(null)
const canvasContainer = ref(null)
const isDragging = ref(false)
const imageUrl = ref('')
const imageObj = ref(null)

// 文字内容
const topText = ref('顶部文字')
const bottomText = ref('底部文字')
const customTexts = ref([])

// 文字样式
const textStyle = ref({
  font: 'Microsoft YaHei',
  size: 36,
  color: '#ffffff',
  strokeColor: '#000000',
  strokeWidth: 2
})

// 预设模板
const memeTemplates = [
  {
    name: '滑稽',
    url: 'https://i.postimg.cc/W4YWgDP8/huaji.jpg'
  },
  {
    name: '狗头',
    url: 'https://i.postimg.cc/J0SvvQFK/doge.jpg'
  },
  {
    name: '小丑龙',
    url: 'https://i.postimg.cc/VsHGCKRk/long.jpg'
  },
  {
    name: '呆呆',
    url: 'https://i.postimg.cc/C1N9hZct/daidai.jpg'
  },
  {
    name: '疑惑',
    url: 'https://i.postimg.cc/2yHCYgn1/yihuo.jpg'
  },
  {
    name: '惊讶',
    url: 'https://i.postimg.cc/ZqXWF2xq/jingya.jpg'
  },
  {
    name: '咆哮',
    url: 'https://i.postimg.cc/t4bZLj8Z/paoxiao.jpg'
  },
  {
    name: '流泪',
    url: 'https://i.postimg.cc/fRdsPQXW/liulei.jpg'
  }
]

// 当前拖拽的文本索引
const dragIndex = ref(-1)
let dragStartX = 0
let dragStartY = 0
let textStartX = 0
let textStartY = 0

// 触发文件选择
function triggerFileInput() {
  fileInput.value.click()
}

// 处理文件选择
function handleFileChange(event) {
  const file = event.target.files[0]
  if (file && file.type.match('image.*')) {
    loadImage(file)
  }
}

// 处理拖放
function handleDrop(event) {
  isDragging.value = false
  const file = event.dataTransfer.files[0]
  if (file && file.type.match('image.*')) {
    loadImage(file)
  }
}

// 加载图片
function loadImage(file) {
  const reader = new FileReader()
  reader.onload = (e) => {
    imageUrl.value = e.target.result
    nextTick(() => {
      initCanvas()
    })
  }
  reader.readAsDataURL(file)
}

// 初始化画布
function initCanvas() {
  const img = new Image()
  img.onload = () => {
    imageObj.value = img
    
    // 设置画布尺寸
    const maxWidth = canvasContainer.value.clientWidth
    let width = img.width
    let height = img.height
    
    if (width > maxWidth) {
      const ratio = maxWidth / width
      width = maxWidth
      height = height * ratio
    }
    
    canvas.value.width = width
    canvas.value.height = height
    
    drawMeme()
  }
  img.src = imageUrl.value
}

// 绘制表情包
function drawMeme() {
  if (!canvas.value || !imageObj.value) return
  
  const ctx = canvas.value.getContext('2d')
  const { width, height } = canvas.value
  
  // 清除画布
  ctx.clearRect(0, 0, width, height)
  
  // 绘制图片
  ctx.drawImage(imageObj.value, 0, 0, width, height)
  
  // 设置文字样式
  ctx.textAlign = 'center'
  ctx.font = `${textStyle.value.size}px ${textStyle.value.font}`
  ctx.fillStyle = textStyle.value.color
  ctx.strokeStyle = textStyle.value.strokeColor
  ctx.lineWidth = textStyle.value.strokeWidth
  
  // 绘制顶部文字
  if (topText.value) {
    drawTextWithWrapping(ctx, topText.value, width / 2, textStyle.value.size + 10, width - 20, 'top')
  }
  
  // 绘制底部文字
  if (bottomText.value) {
    drawTextWithWrapping(ctx, bottomText.value, width / 2, height - 20, width - 20, 'bottom')
  }
  
  // 绘制自定义文字
  customTexts.value.forEach(text => {
    ctx.fillStyle = text.color || textStyle.value.color
    drawText(ctx, text.content, text.x, text.y)
  })
}

// 绘制文字（带描边）
function drawText(ctx, text, x, y) {
  if (textStyle.value.strokeWidth > 0) {
    ctx.strokeText(text, x, y)
  }
  ctx.fillText(text, x, y)
}

// 绘制自动换行文字
function drawTextWithWrapping(ctx, text, x, y, maxWidth, position) {
  const words = text.split(' ')
  const lines = []
  let currentLine = words[0]
  
  for (let i = 1; i < words.length; i++) {
    const word = words[i]
    const width = ctx.measureText(currentLine + ' ' + word).width
    if (width < maxWidth) {
      currentLine += ' ' + word
    } else {
      lines.push(currentLine)
      currentLine = word
    }
  }
  lines.push(currentLine)
  
  // 调整顶部和底部文字的位置
  let lineY = y
  if (position === 'top') {
    lines.forEach(line => {
      drawText(ctx, line, x, lineY)
      lineY += textStyle.value.size + 5
    })
  } else {
    lineY -= (lines.length - 1) * (textStyle.value.size + 5)
    lines.forEach(line => {
      drawText(ctx, line, x, lineY)
      lineY += textStyle.value.size + 5
    })
  }
}

// 添加自定义文字
function addCustomText() {
  const { width, height } = canvas.value
  customTexts.value.push({
    content: '自定义文字',
    x: width / 2,
    y: height / 2,
    color: textStyle.value.color
  })
  drawMeme()
}

// 移除自定义文字
function removeCustomText(index) {
  customTexts.value.splice(index, 1)
  drawMeme()
}

// 开始拖拽文字
function startDragging(event) {
  const rect = canvas.value.getBoundingClientRect()
  const x = (event.clientX || event.touches[0].clientX) - rect.left
  const y = (event.clientY || event.touches[0].clientY) - rect.top
  
  // 检查是否点击了自定义文字
  for (let i = customTexts.value.length - 1; i >= 0; i--) {
    const text = customTexts.value[i]
    const ctx = canvas.value.getContext('2d')
    const metrics = ctx.measureText(text.content)
    const width = metrics.width
    const height = textStyle.value.size
    
    if (
      x >= text.x - width / 2 - 10 &&
      x <= text.x + width / 2 + 10 &&
      y >= text.y - height &&
      y <= text.y + 10
    ) {
      dragIndex.value = i
      dragStartX = x
      dragStartY = y
      textStartX = text.x
      textStartY = text.y
      
      // 添加移动和结束拖拽事件监听
      document.addEventListener('mousemove', moveText)
      document.addEventListener('mouseup', stopDragging)
      document.addEventListener('touchmove', moveText, { passive: false })
      document.addEventListener('touchend', stopDragging)
      
      // 阻止事件冒泡
      event.preventDefault()
      break
    }
  }
}

// 移动文字
function moveText(event) {
  if (dragIndex.value === -1) return
  
  event.preventDefault()
  const rect = canvas.value.getBoundingClientRect()
  const x = (event.clientX || event.touches[0].clientX) - rect.left
  const y = (event.clientY || event.touches[0].clientY) - rect.top
  
  const dx = x - dragStartX
  const dy = y - dragStartY
  
  customTexts.value[dragIndex.value].x = textStartX + dx
  customTexts.value[dragIndex.value].y = textStartY + dy
  
  drawMeme()
}

// 停止拖拽
function stopDragging() {
  dragIndex.value = -1
  document.removeEventListener('mousemove', moveText)
  document.removeEventListener('mouseup', stopDragging)
  document.removeEventListener('touchmove', moveText)
  document.removeEventListener('touchend', stopDragging)
}

// 下载表情包
function downloadMeme(format) {
  let mimeType = 'image/png'
  let extension = '.png'
  let quality = 1
  
  if (format === 'jpg') {
    mimeType = 'image/jpeg'
    extension = '.jpg'
    quality = 0.9
  }
  
  const dataUrl = canvas.value.toDataURL(mimeType, quality)
  const link = document.createElement('a')
  link.href = dataUrl
  link.download = `meme-${new Date().getTime()}${extension}`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 复制到剪贴板
function copyToClipboard() {
  canvas.value.toBlob(blob => {
    try {
      const item = new ClipboardItem({ 'image/png': blob })
      navigator.clipboard.write([item])
        .then(() => {
          alert('图片已复制到剪贴板')
        })
        .catch(err => {
          console.error('复制失败:', err)
          alert('复制失败，请尝试保存图片')
        })
    } catch (err) {
      console.error('不支持的操作:', err)
      alert('您的浏览器不支持复制图片到剪贴板，请尝试保存图片')
    }
  })
}

// 重置图片
function resetImage() {
  if (imageUrl.value) {
    initCanvas()
    topText.value = '顶部文字'
    bottomText.value = '底部文字'
    customTexts.value = []
  }
}

// 选择新图片
function chooseNewImage() {
  imageUrl.value = ''
  imageObj.value = null
  topText.value = '顶部文字'
  bottomText.value = '底部文字'
  customTexts.value = []
}

// 使用模板
function useTemplate(template) {
  fetch(template.url)
    .then(response => {
      if (!response.ok) throw new Error('Network response was not ok')
      return response.blob()
    })
    .then(blob => {
      loadImage(blob)
    })
    .catch(error => {
      console.error('加载模板失败:', error)
      alert('加载模板失败，请尝试上传本地图片')
    })
}

// 组件卸载时移除事件监听
onMounted(() => {
  window.addEventListener('resize', () => {
    if (imageObj.value) {
      nextTick(() => {
        initCanvas()
      })
    }
  })
})
</script> 